package com.jfinal.plugin.activerecord.sql;


import java.util.*;

/**
 * @author CHEN
 */
public class SqlUpdate extends SqlObject<SqlUpdate> {

    public static final String UPDATE = " UPDATE ";

    public static final String SET = " SET ";

    private Map<String, Object> columnMap = new HashMap<>();

    public SqlUpdate(String tableName) {
        this.tableName = tableName;
    }


    public SqlUpdate set(String column, Object value) {
        this.columnMap.put(column, value);
        return this;
    }

    public SqlUpdate set(Map<String, Object> columnMap) {
        this.columnMap.putAll(columnMap);
        return this;
    }

    public String getSetColumnSql() {
        StringBuffer sql = new StringBuffer();
        boolean isFirst = true;
        for (Map.Entry<String, Object> e : columnMap.entrySet()) {
            String colName = e.getKey();
            if (isFirst) {
                isFirst = false;
            } else {
                sql.append(", ");
            }
            sql.append('`').append(colName).append("` = ? ");
        }
        return sql.toString();
    }

    @Override
    public Object[] getParams() {
        List<Object> params = new ArrayList<>();
        params.addAll(columnMap.values());
        params.addAll(Arrays.asList(this.spec.getParams()));
        return params.toArray();
    }


    @Override
    public String toSql() {
        return UPDATE + tableName + SET + getSetColumnSql() + getSpecSql();
    }

    public static void main(String[] args) {
        SqlObject sql = new SqlUpdate("user").set("name", "aa").set("age", 10).where("name=?", "cc");
        System.out.println(sql.toSql());
        System.out.println(sql.getParams().length);
    }

}
